package jsyf.oa.web.wechat.service_account.controller;

import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import jsyf.oa.facade.wechat.service_account.WechatTemplateFacade;
import jsyf.oa.facade.wechat.service_account.WechatUserFacade;
import jsyf.oa.web.wechat.service_account.pojo.CustomerMessage;
import jsyf.oa.web.wechat.service_account.response.TextResponse;
import jsyf.oa.web.wechat.service_account.utils.MessageUtil;
import jsyf.oa.web.wechat.service_account.utils.SignUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

@SuppressWarnings("all")
@Api(value = "服务号-用于微信对接，不能被调用", description = "服务号-用于微信对接，不能被调用")
@Controller
@RequestMapping("/weChatCore")
public class CoreController {

    @Resource
    private WechatUserFacade wechatUserFacade;
    @Resource
    private WechatTemplateFacade wechatTemplateFacade;

    @RequestMapping(method = RequestMethod.GET)
    public void weChat(HttpServletRequest request, HttpServletResponse response) {
        PrintWriter out = null;
        // 微信加密签名
        String signature = request.getParameter("signature");
        // 时间戳
        String timestamp = request.getParameter("timestamp");
        // 随机数
        String nonce = request.getParameter("nonce");
        // 随机字符串
        String echostr = request.getParameter("echostr");
        try {
            out = response.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
        if (SignUtil.checkSignature(signature, timestamp, nonce)) {
            out.print(echostr);
        }

        out.close();
    }


    @RequestMapping(method =RequestMethod.POST)
    public void dispose(HttpServletRequest request, HttpServletResponse response){
        // 消息的接收、处理、响应
        // 将请求、响应的编码均设置为UTF-8（防止中文乱码）
        try {
            request.setCharacterEncoding("UTF-8");
            response.setCharacterEncoding("UTF-8");
            String respXml = processRequest(request);
            // 响应消息
            PrintWriter printWriter = response.getWriter();
            printWriter.print(respXml);
            printWriter.close();

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public String processRequest(HttpServletRequest request) {
        // xml格式的消息数据
        String respXml = null;
        // 默认返回的文本消息内容
        String respContent = "";
        try {
            // 调用parseXml方法解析请求消息
            Map<String, String> requestMap = MessageUtil.parseXml(request);
            // 发送方帐号
            String fromUserName = requestMap.get("FromUserName");
            // 开发者微信号
            String toUserName = requestMap.get("ToUserName");
            // 消息类型
            String msgType = requestMap.get("MsgType");
            //  文本消息内容
            String content = requestMap.get("Content");
            // 回复文本消息
            TextResponse textResponse = new TextResponse();
            textResponse.setToUserName(fromUserName);
            textResponse.setFromUserName(toUserName);
            textResponse.setCreateTime(new Date().getTime());
            textResponse.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);

            // 文本消息
            if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_TEXT)) {

                respContent = "";
                int isContain = content.indexOf("bd+");
                if (isContain != -1){
                    content = content.replace("bd+","");
                    if (isChinaPhoneLegal(content)){
                        wechatUserFacade.updateUserByCustomerTel(fromUserName, content);
                        respContent = "绑定成功";
                        /**
                         * 绑定且查询手机号是否已经存在
                         */
//                        JSONObject jsonObject = wechatUserFacade.getOAUserByPhone(content);
//                        if (jsonObject != null && jsonObject.size() != 0){
//                            String name = jsonObject.getString("name");
//                            respContent = "绑定成功";
//                            wechatTemplateFacade.sendPrivateTemplate("{\"data\":{\"first\":{\"color\":\"#ff0000\",\"value\":\"你好"+name+"\"},\"keyword1\":{\"color\":\"#173177\",\"value\":\"name\"},\"keyword2\":{\"color\":\"#173177\",\"value\":\"time\"},\"keyword3\":{\"color\":\"#173177\",\"value\":\"address\"},\"keyword4\":{\"color\":\"#173177\",\"value\":\"info\"},\"remark\":{\"color\":\"#999999\",\"value\":\"remark\"}},\"template_id\":\"kFOmHKe5L1D5m37y6wOmhE-6OwGqedPS3aVykYiwP8g\",\"touser\":\"oWkJW0_kcE_Cr4w92ZZZ1gKe0AEo\",\"url\":\"http://\"}");
//                        } else {
//                            respContent = "你还没有注册";
//                        }
                    }
                }

                CustomerMessage customer=new CustomerMessage();
                customer.setToUserName(fromUserName);
                customer.setFromUserName(toUserName);
                customer.setCreateTime(new Date().getTime());
                customer.setMsgType("transfer_customer_service");
                return MessageUtil.customerMessageToXml(customer);
            }
            // 图片消息
            else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_IMAGE)) {
                respContent = "你发送了一张图片";
            }
            // 语音消息
            else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_VOICE)) {
                respContent = "你发送了一条语音";
            }
            // 视频消息
            else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_VIDEO)) {
                respContent = "你发送了一条视频";
            }
            // 视频消息
            else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_SHORTVIDEO)) {
                respContent = "你发送了一条小视频";
            }
            // 地理位置消息
            else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_LOCATION)) {
                respContent = "你发送了当前的位置";
            }
            // 链接消息
            else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_LINK)) {
                respContent = "你发送了一个链接";
            }
            // 事件推送
            else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_EVENT)) {
                //  事件类型
                String eventType = requestMap.get("Event");
                // 关注
                if (eventType.equals(MessageUtil.EVENT_TYPE_SUBSCRIBE)) {
                    respContent = "感谢关注滚滚向前服务";

                    String eventKey = requestMap.get("EventKey");
                    if (eventKey != null && eventKey.contains("qrscene_")){
                        eventKey = eventKey.replace("qrscene_","");

                        JSONObject jsonObject = (JSONObject) JSONObject.parse(eventKey);
                        String customerTel = jsonObject.getString("customerTel");
                        if (!wechatUserFacade.isExit(fromUserName)){//  客户表中不存在则存储
                            wechatUserFacade.saveUserByeventKey(fromUserName, eventKey);
                        }else if (!wechatUserFacade.isExitByCustomerTel(customerTel)){//   非（客户已关注且已绑定此手机号）
                            wechatUserFacade.updateUserByEventKey(fromUserName, eventKey);
                        }
                    }

                    boolean isExit = wechatUserFacade.isExit(fromUserName);
                    if (isExit){//  用户存在则将用户更新为已关注
                        wechatUserFacade.updateUserByOpenId(fromUserName,1);
                    }else {//   用户不存在则存储
                        wechatUserFacade.saveUserByOpenId(fromUserName);
                    }
                }
                // 取消关注
                else if (eventType.equals(MessageUtil.EVENT_TYPE_UNSUBSCRIBE)) {
                    /**
                     * 用户取消关注，需要更新user表，在user表中标识为未关注
                     */
                    //    当用户取消关注且用户之前存在则更新
                    boolean isExit = wechatUserFacade.isExit(fromUserName);
                    if (isExit){
                        wechatUserFacade.updateUserByOpenId(fromUserName, 0);
                    }
                }
                // 扫描带参数二维码
                else if (eventType.equals(MessageUtil.EVENT_TYPE_SCAN)) {
                    // TODO 处理扫描带参数二维码事件
                    String eventKey = requestMap.get("EventKey");
                    respContent = "欢迎光临滚滚向前服务";
                }
                // 上报地理位置
                else if (eventType.equals(MessageUtil.EVENT_TYPE_LOCATION)) {
                    // TODO 处理上报地理位置事件
                }
                // 自定义菜单
                else if (eventType.equals(MessageUtil.EVENT_TYPE_CLICK)) {
                    /**
                     * 回复链接消息
                     */
//                    Article article = new Article();
//                    article.setTitle("二手汇工程机械网");
//                    article.setPicUrl("http://esh.yingfeng365.com/Images/home/logo2.png");
//                    article.setUrl("http://esh.yingfeng365.com");
//                    article.setDescription("二手汇工程机械网-一家专门做二手工程机械的网站");
//                    ArticleResponse articleResponse = new ArticleResponse();
//                    articleResponse.setArticles(new Article[] {article});
//                    articleResponse.setArticleCount(1);
//                    articleResponse.setToUserName(fromUserName);
//                    articleResponse.setFromUserName(toUserName);
//                    articleResponse.setCreateTime(new Date().getTime());
//                    articleResponse.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_NEWS);
//
//                    respXml = MessageUtil.messageToXml(articleResponse);
//                    return respXml;
                }
            }
            // 设置文本消息的内容
            textResponse.setContent(respContent);
            // 将文本消息对象转换成xml
            respXml = MessageUtil.messageToXml(textResponse);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return respXml;
    }

    public static boolean isChinaPhoneLegal(String str) throws PatternSyntaxException {
        String regExp = "^((13[0-9])|(15[^4])|(18[0,2,3,5-9])|(17[0-8])|(147))\\d{8}$";
        Pattern p = Pattern.compile(regExp);
        Matcher m = p.matcher(str);
        return m.matches();
    }
}